package com.xl98.config;


import com.xl98.entity.Groups;
import com.xl98.entity.GroupsMsgContent;
import com.xl98.entity.MsgContent;
import com.xl98.entity.User;
import com.xl98.service.GroupsMsgContentService;
import com.xl98.service.GroupsService;
import com.xl98.service.MsgContentService;
import com.xl98.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket/{groupId}/{username}",configurator = WebSocketConfig.class)
@Component
public class MyWebSocket {
    private String username;
    private String groupId;
    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("username") String username,@PathParam("groupId") String groupId) {
        this.groupId = groupId;
        this.session = session;
        this.username = username;
        webSocketSet.add(this);//加入set中
        System.out.println(date.format(new Date()) + " " + groupId + " 有新连接加入！" + username );
        this.session.getAsyncRemote().sendText("恭喜您成功连接 "+groupId+" -->");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session,@PathParam("username") String username,@PathParam("groupId") String groupId) {
        //发送信息
        broadcast(date.format(new Date()) + "\n" + username + ":" + message + "\n", groupId);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void broadcast(String message, String groupId) {
        for (MyWebSocket item : webSocketSet) {
            if(item.groupId.equals(groupId) ){
                item.session.getAsyncRemote().sendText(message);//异步发送消息.
            }
        }
    }
}
